<?php

class User {

	public $UID;

	function __construct($uid = null) {
		if ($uid == null) {
			$this->identify();
		} else {
			$this->UID = $uid;
		}
	}

	function identify() {
		// See if our session is activated
		$this->UID = $this->activate_user(
				$_COOKIE[Config::$cookie_prefix . 'username'],
				$_COOKIE[Config::$cookie_prefix . 'password']
				);
	}

	function activate_user($user, $pass) {
		// Remove all stored session variables.
		session_unset();

		if (!$user || !$pass) {
			return $this->create_user();
		}

		$stmt = Storage::$DB->prepare("SELECT uid FROM {prefix}users WHERE username = ? AND password = ? LIMIT 1");

		$stmt->execute(array($user, $pass));

		$row = $stmt->fetch();

		if (!$row) { // Not valid user info, new user account
			return $this->create_user();
		}

		return $row["uid"];
	}

	function create_user() {
		$username = uniqid('', true);
		$password = $this->generate_password();
		$user_ip = $_SERVER['REMOTE_ADDR'];

		$result = Storage::$DB->insert('users', array(
					"username" => $username,
					"password" => $password,
					"first_seen" => time(),
					"last_seen" => time()
				));

		if ($result) { // Our user has been created
			// 31556926 = 1 year in seconds
			setcookie(Config::$cookie_prefix . "username", $username, time() + 31556926, "/");
			setcookie(Config::$cookie_prefix . "password", $password, time() + 31556926, "/");
			return Storage::$DB->lastInsertId();
		} else { // Nope?
			URL::show_error(_("ACC_CREATE_FAIL"));
			return false;
		}
	}

	function generate_password() {
		$characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
		$password = '';

		for ($i = 0; $i < 32; ++$i) {
			$password .= $characters[array_rand($characters)];
		}
		return $password;
	}

}

?>
